package com.tianruan.dc.modules.generator.utils;

import com.tianruan.dc.common.utils.DateUtils;
import com.tianruan.dc.modules.generator.entity.ColumnEntity;
import com.tianruan.dc.modules.generator.entity.TableEntity;
import com.tianruan.dc.modules.generator.exception.GeneratorException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import org.apache.commons.configuration.Configuration;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器   工具类
 */
public class GenUtils {

    private static String currentTableName;

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/DO.java.vm");
        templates.add("template/DTO.java.vm");
        templates.add("template/VO.java.vm");

        templates.add("template/Mapper.xml.vm");

//        templates.add("template/menu.sql.vm");

        templates.add("template/Service.java.vm");
        templates.add("template/ServiceImpl.java.vm");
        templates.add("template/Controller.java.vm");
        templates.add("template/Mapper.java.vm");

//        templates.add("template/index.vue.vm");
//        templates.add("template/add-or-update.vue.vm");
        return templates;
    }

    public static List<String> getMongoChildTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/MongoChildrenEntity.java.vm");
        return templates;
    }

    /**
     * 生成代码
     */
    public static void generatorCode(String moduleName,
                                     String author,
                                     String email,
                                     Map<String, String> table,
                                     List<Map<String, String>> columns,
                                     String[] tablePrefix,
                                     ZipOutputStream zip) {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        boolean hasList = false;
        //表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));

        String[] tablePrefixes = tablePrefix;
        //表名转换成Java类名
        if (CollectionUtils.isEmpty(Arrays.asList(tablePrefix))) {
            tablePrefixes = config.getStringArray("tablePrefix");
        }
        // 表名转类名
        String tableName = tableEntity.getTableName();
        String className = tableToJava(tableName, tablePrefixes);
        // 开头大写类名
        tableEntity.setClassName(className);
        // 开头小写类名
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<ColumnEntity> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            // 查询表字段
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), columnToJava(columnEntity.getDataType()));
            columnEntity.setAttrType(attrType);


            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasList && "array".equals(columnEntity.getExtra())) {
                hasList = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tableEntity.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        // 修改package
        String aPackage = config.getString("package");
        // api模块包名
        String apiPackage = config.getString("package");
        if (StringUtils.isBlank(moduleName)) {
            moduleName = config.getString("moduleName");
        }
        // 模块名称
        String[] modules = moduleName.split("\\.");
        for (int i = 0; i < modules.length - 1; i++) {
            aPackage += "." + modules[i];
            apiPackage += "." + modules[i];
        }
        apiPackage += ".api";
        moduleName = modules[modules.length - 1];

        List<String> excludeColumns = Arrays.asList("id", "create_by", "create_date");
        List<ColumnEntity> updateColumns = new ArrayList<>();
        List<ColumnEntity> columnsList = tableEntity.getColumns();
        for (ColumnEntity columnEntity: columnsList) {
            if (!excludeColumns.contains(columnEntity.getColumnName())) {
                updateColumns.add(columnEntity);
            }
        }


        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        // 主路径
        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "com.trgzs.cloud" : mainPath;
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        // 表名
        map.put("tableName", tableEntity.getTableName());
        //
        map.put("comments", tableEntity.getComments());
        // 主键
        map.put("pk", tableEntity.getPk());
        // 类名（大写开头）
        map.put("className", tableEntity.getClassName());
        // 类名（小写开头）
        map.put("classname", tableEntity.getClassname());
        // 路径
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        // 字段
        map.put("columns", tableEntity.getColumns());
        // 更新字段
        map.put("updateColumns", updateColumns);
        // 是否存在BigDecimal类型
        map.put("hasBigDecimal", hasBigDecimal);
        // 是否存在List类型
        map.put("hasList", hasList);

        map.put("mainPath", mainPath);
        map.put("package", aPackage);
        map.put("apiPackage", apiPackage);
        if (!StringUtils.isNotBlank(author)) {
            author = config.getString("author");
        }
        if (!StringUtils.isNotBlank(email)) {
            email = config.getString("email");
        }
        // 模块名称
        map.put("moduleName", moduleName);
        // 作者
        map.put("author", author);
        // 邮箱
        map.put("email", email);
        // 生成时间
        map.put("datetime", DateUtils.formatDateTime(new Date()));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), aPackage, moduleName)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new GeneratorException("渲染模板失败，表名：" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String[] tablePrefixArray) {
        if (null != tablePrefixArray && tablePrefixArray.length > 0) {
            for (String tablePrefix : tablePrefixArray) {
                  if (tableName.startsWith(tablePrefix)){
                    tableName = tableName.replaceFirst(tablePrefix, "");
                }
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new GeneratorException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }
//        if (template.contains("MongoChildrenEntity.java.vm")) {
//            return packagePath + "entity" + File.separator + "inner" + File.separator + currentTableName+ File.separator + splitInnerName(className)+ "InnerEntity.java";
//        }
//        if (template.contains("Entity.java.vm") || template.contains("MongoEntity.java.vm")) {
//            return packagePath + "entity" + File.separator + className + "Entity.java";
//        }

        if (template.contains("DO.java.vm")) {
            return packagePath + "entity" + File.separator + "db" + File.separator + className + "DO.java";
        }
        if (template.contains("DTO.java.vm")) {
            return packagePath + "entity" + File.separator + "dto" + File.separator + className + "DTO.java";
        }
        if (template.contains("VO.java.vm")) {
            return packagePath + "entity" + File.separator + "vo" + File.separator + className + "VO.java";
        }


        if (template.contains("Mapper.java.vm")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }

        if (template.contains("Service.java.vm")) {
            return packagePath + "service" + File.separator + "I" + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.vm")) {
            return packagePath + "api" + File.separator + className + "Controller.java";
        }

        if (template.contains("Mapper.xml.vm")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "Mapper.xml";
        }
//
//        if (template.contains("menu.sql.vm")) {
//            return className.toLowerCase() + "_menu.sql";
//        }
//
//        if (template.contains("index.vue.vm")) {
//            return "main" + File.separator + "resources" + File.separator + "src" + File.separator + "views" + File.separator + "modules" +
//                    File.separator + moduleName + File.separator + className.toLowerCase() + ".vue";
//        }
//
//        if (template.contains("add-or-update.vue.vm")) {
//            return "main" + File.separator + "resources" + File.separator + "src" + File.separator + "views" + File.separator + "modules" +
//                    File.separator + moduleName + File.separator + className.toLowerCase() + "-add-or-update.vue";
//        }

        return null;
    }

    private static String splitInnerName(String name){
          name = name.replaceAll("\\.","_");
          return name;
    }
}
